<script setup lang='ts'>
  import { nextTick, reactive, ref } from 'vue';
  import { propApi } from '@/api/controller';
  import { ToastSuccess, ToastWarning, Toastloading, allNumber } from '@/utils/public';
  import { getSummaries } from '@/utils';
  import { ElMessageBox } from 'element-plus';
  import serachGift from '@/components/serachGift/index.vue';
  import xmImage from '@/components/xmImage/index.vue';
  import xmUpload from '@/components/Upload/xm-upload.vue';
  const $emit = defineEmits(['updateList'])
  const formLabelWidth = '160px'
  const dataForm = ref()
  const action = reactive({
    dialogVisible:false,
    dialogFormVisible:false,
    disabled:false,
    title:'',
    pool_id:0,
    giftInfo:{} as any,
    poolList:[] as Array<any>,
    rate_num:1,
    rateList:[] as Array<any>,
    banner:{
      img_url:'',
      jump_url:''
    }
  })
  interface formQuert {
    id:number
    item_no:number
    gift_id:number
    gift_num:number
    out_rate:number
  }
  let form = reactive({} as formQuert)
  const formRules = {
    gift_id: [{ required: true, trigger: "blur", message: "请输入礼物ID" }],
    gift_num: [{ required: true, trigger: "blur", message: "请输入礼物数量" }],
    out_rate: [{ required: true, trigger: "blur", message: "请输入千分位整数礼物概率" }],
  }
  const handleForm = (row:any = {})=>{
    const { item_no, gift_id='', gift_num='', out_rate='', id=0, gift_image='', gift_name='', gift_price='' } = row
    if(!item_no) return ToastWarning('缺少 序号 item_no')
    if(!id) return ToastWarning('缺少 id')
    form.item_no = item_no
    form.id = id
    if(gift_id) {
      Object.assign(form,{
        gift_id,
        gift_num,
        out_rate
      })
      action.giftInfo = {
        name:gift_name,
        image:gift_image,
        price:gift_price
      }
    }
    action.dialogFormVisible = true
  }
  const handleFormSubmit = ()=>{
    dataForm.value.validate(async(valid:any)=>{
      if(!valid) return
      const index = action.poolList.findIndex(res=>res.item_no == form.item_no)
      if(index < 0) return
      const { name='', image='', price=0 } = action.giftInfo
      const { out_rate } = form
      action.poolList[index] = {
        gift_name:name,
        gift_image:image,
        gift_price:price,
        ...form,
        out_rate_text:out_rate > 0 ? (out_rate/100).toFixed(2) : out_rate
      }
      closeFormDialog()
    })
  }
  const submitPoolConfig = ()=>{
    const loading = Toastloading()
    const pool_list = action.poolList.map(res=>{
      const { id, gift_id, gift_num, out_rate } = res
      return {
        id, gift_id, gift_num, out_rate
      }
    })
    propApi.colorGiftPoolConfigSave({
      pool_id:action.pool_id,
      pool_list:JSON.stringify(pool_list)
    }).then(async()=>{
      ToastSuccess('保存礼物池配置成功')
      loading.close()
      await getList()
      closeDialog()
    }).catch(()=>{
      loading.close()
    })
  }
  const addPoolRate = ()=>{
    const loading = Toastloading()
    const pool_list = action.poolList.map(res=>{
      const { id, gift_id, gift_num, out_rate } = res
      return {
        id, gift_id, gift_num, out_rate
      }
    })
    propApi.addPoolRate({
      pool_id:action.pool_id,
      pool_list:JSON.stringify(pool_list)
    }).then(async()=>{
      ToastSuccess('新增礼物池概率成功')
      loading.close()
      await getPoolRateList()
      action.rate_num = action.rateList[action.rateList.length - 1].rate_num
      await getList()
    }).catch(()=>{
      loading.close()
    })
  }
  const delRate = ()=>{
    const { name } = action.rateList.find(res=> res.rate_num == action.rate_num)
    ElMessageBox.confirm(`确定礼物池类型：${name}吗?`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      const loading = Toastloading();
      propApi.color_gift_rate_del({
        pool_id:action.pool_id,
        rate_num:action.rate_num
      }).then(async()=>{
        ToastSuccess("删除成功!");
        loading.close();
        await getPoolRateList()
        getList();
      }).catch(()=>{
        loading.close();
      })
    }).catch(() => {});
  }
  const getList = async()=> {
    const loading = Toastloading()
    const res = await propApi.colorGiftPoolConfigList({
      pool_id:action.pool_id,
      rate_num:action.rate_num
    })
    await color_gift_rate_banner()
    loading.close()
    const { data={} } = res || {}
    action.poolList = data.map((res:any)=>{
      const { out_rate=0 } = res
      return {
        ...res,
        out_rate_text:out_rate > 0 ? (out_rate/100).toFixed(2) : out_rate
      }
    })
  }
  const getPoolRateList = async()=>{
    const loading = Toastloading()
    const res = await propApi.getPoolRateList({
      pool_id:action.pool_id,
    })
    loading.close()
    const { data } = res
    action.rateList = data
  }
  const color_gift_rate_banner = async()=>{
    const res = await propApi.color_gift_rate_banner({
      pool_id:action.pool_id,
      rate_num:action.rate_num
    })
    const { img_url='', jump_url='' } = res?.data || {}
    action.banner = {
      img_url,
      jump_url
    }
  }
  const submitBanner = async()=>{
    const { img_url='', jump_url='' } = action.banner
    if(!img_url) return ToastWarning('请上传礼物banner图片')
    if(!jump_url) return ToastWarning('请输入礼物banner跳转链接')
    const loading = Toastloading('保存礼物banner中')
    const res = await propApi.color_gift_rate_banner_change({
      pool_id:action.pool_id,
      rate_num:action.rate_num,
      img_url,
      jump_url
    })
    loading.close()
    ToastSuccess('保存礼物banner成功')
  }
  const openDialog = async(query:any={})=> {
    const { id=0, pool_name='' } = query
    action.title = `礼物池配置：${pool_name}`
    action.pool_id = id
    await getPoolRateList()
    await getList()
    action.dialogVisible = true
  }
  const closeDialog = ()=>{
    action.banner = {
      img_url:'',
      jump_url:''
    }
    action.rateList = []
    action.rate_num = 1
    action.poolList = []
    action.giftInfo = {}
    action.pool_id = 0
    action.dialogVisible = false
  }
  const closeFormDialog = ()=>{
    form = reactive({} as formQuert)
    nextTick(() => {
      dataForm.value.clearValidate();
    });
    action.dialogFormVisible = false
  }
  defineExpose({
    openDialog
  })
</script>

<template>
  <div>
    <el-dialog
      top="7vh"
      class="xm-dialog xm-dialog-cont-y"
      v-model="action.dialogVisible"
      :close-on-click-modal="action.disabled"
      :close-on-press-escape="action.disabled"
      :show-close="action.disabled"
      width="50%"
      :title="action.title">
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <div class="label">礼物池类型：</div>
            <el-select v-model="action.rate_num" @change="getList" placeholder="请选择礼物池类型">
              <el-option
                v-for="item in action.rateList"
                :key="item.rate_num"
                :label="item.name"
                :value="item.rate_num" />
            </el-select>
          </div>
          <div class="labelItem">
            <el-button type="primary" @click="addPoolRate">新增概率</el-button>
          </div>
        </div>
      </div>
      <div class="xm-headTab">
        <div class="labelBox">
          <div class="labelItem">
            <div class="label">礼物banner图片：</div>
            <xmUpload :data={type:5} :limit="1" v-model:fileUrl="action.banner.img_url" />
          </div>
          <div class="labelItem">
            <div class="label">跳转地址：</div>
            <el-input
              v-model="action.banner.jump_url"
              :autosize="{ minRows: 7, maxRows: 7}"
              type="textarea"
              placeholder="请输入跳转地址"
            />
          </div>
          <div class="labelItem">
            <el-button type="primary" @click="submitBanner">保存banner配置</el-button>
          </div>
        </div>
      </div>
      <el-table
        class="xm-TableCenter"
        :data="action.poolList"
        border
        show-summary
        :summary-method="((param:any)=>getSummaries(param,[0,1,2,3,4],[{key:5,unit:'%'}]))"
      >
        <el-table-column width="80" prop="item_no" label="序号" />
        <el-table-column width="80" prop="gift_id" label="礼物ID" />
        <el-table-column min-width="80" prop="gift_name" label="礼物名称" />
        <el-table-column min-width="80" prop="gift_image" label="礼物图片">
          <template #default="scoped">
            <xmImage :src="scoped.row.gift_image" :list="[scoped.row.gift_image]" />
          </template>
        </el-table-column>
        <el-table-column min-width="80" prop="gift_price" label="礼物价格" />
        <el-table-column min-width="80" prop="out_rate_text" label="外显概率">
          <template #default="scoped">
            {{ scoped.row.out_rate_text }}%
          </template>
        </el-table-column>
        <el-table-column min-width="80" prop="gift_num" label="总数量" />
        <el-table-column width="120"  label="操作">
          <template #default="scoped">
            <el-button type="primary" @click="handleForm(scoped.row)">编辑礼物池</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="danger" @click="delRate">删除配置类型</el-button>
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="submitPoolConfig">保存配置</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      top="12vh"
      class="xm-dialog input-width"
      v-model="action.dialogFormVisible"
      :close-on-click-modal="action.disabled"
      :show-close="action.disabled"
      :close-on-press-escape="action.disabled"
      width="35%"
      title="编辑礼物池礼物">
      <el-form ref="dataForm" :model="form" :rules="formRules">
        <el-form-item :label-width="formLabelWidth" label="礼物ID" prop="gift_id">
          <!-- <serachGift :gift_type="1" v-model:gift_id="form.gift_id" v-model:gift_info="action.giftInfo" /> -->
          <serachGift
          version="0.0.1"
          :show_gift_type="[1,9]"
          v-model:gift_id="form.gift_id"
          v-model:gift_info="action.giftInfo" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="礼物数量" prop="gift_num">
          <el-input v-model="form.gift_num" @input="allNumber(form,'gift_num')" placeholder="请输入礼物数量"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="外显礼物概率(千分位)" prop="out_rate">
          <el-input v-model="form.out_rate" @input="allNumber(form,'out_rate')" placeholder="请输入千分位整数礼物概率"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeFormDialog">取 消</el-button>
          <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
